<?php
class AuthComponent{
	var $controller;
	var $model_name='User';
	var $allowedActions=array();
	function initialize($controller){
		$controller->Auth=$this;
		$this->controller=$controller;
		$this->model=$this->controller->{$this->model_name};
	}
	function startup(){
		if($this->user()==null){
			$controller=&$this->controller;
			if(!$controller->Acl->check($this->user(),$this->action(),$this->allowedActions)){
				if($controller->RequestHandler->isAjax()){
					$controller->set('problem',array("success"=>0,"errmsg"=>"Not logged in"));
					$controller->set('json',array("problem"));
					$controller->render();
				}else{
					header("Location: http://".$GLOBALS['_SERVER']['SERVER_HOST'].'/'.$GLOBALS['ENV']['base']);
				}
			}
		}
	}
	function user(){
		$data=$this->controller->Session->read("Auth");
		if(isset($data['User'])){
			return $data;
		}else{
			return null;
		}
	}
	function login($data){
		$condition=array('conditions'=>array('username'=>$data['username']));
		$result=$this->model->find('first',$condition);
		if(empty($result)){
			return false;
		}
		if($this->password($data['padssword']==$result[$model_name]['password'])){
			$this->controller->Session->write("Auth",$result);
			return true;
		}else{
			return false;
		}
	}
	function password($str){
		return sha1($str);
	}
	function logout(){
		$this->controller->Session->write("Auth",null);
		return true;
	}
	function action(){
		return $GLOBALS['ENV']['params']['action'];
	}
}